<template>
	<view class="goodsDetails">
		<shuffling :info="shufflingData"/>
		<view class="synopsis">
			<view class="name">{{ detailsData.productName }}</view>
			<view class="price">
				<text>¥{{ detailsData.salePrice }}</text>
				<text>¥{{ detailsData.originalPrice }}</text>
			</view>
		</view>
		
		<view class="details">
			<view class="title">商品详情</view>
			<view class="rich-text">
				<rich-text :nodes="nodes" @itemclick="richTextClick"></rich-text>
			</view>
		</view>
		
		<view class="goods-nav">
			<uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup"  @click="onClick" @buttonClick="buttonClick" />
		</view>
		
		<uni-popup ref="popup" type="bottom">
			<view class="buy">
				<view class="close" @click="handleClone">
					<uni-icons type="closeempty" color="#666666" size="26"></uni-icons>
				</view>
				<view class="order-details">
					<view class="left">
						<image :src="detailsData.headImg" mode="widthFix"></image>
					</view>
					<view class="right">
						<view class="price">¥{{ detailsData.salePrice }}</view>
						<view class="inventory">库存{{ detailsData.stock }}件</view>
					</view>
				</view>
				
				<view class="quantity">
					<view class="num">数量</view>
					<view class="number-box">
						<uni-number-box v-model="num" @change="handleChange" :min="1" :max="1000000"></uni-number-box>
					</view>
				</view>
				<view class="button">
					<view @click="handleDetermine">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { useStore } from 'vuex';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { classificationQueryAll, cartAddCart } from "@/api/goodsDetails/goodsDetails.js";
import shuffling from "../../components/shuffling.vue";
import parseHtml from "../../utils/common/html-parser.js";

const store = useStore();
const { getters } = useStore();

onLoad(({goodsId}) => {
	detailsId.value = goodsId;
	handleGetDetails(detailsId.value);
});

onShow(() => {
	console.log('onShow');
	options[1].info = getters.getGoodsNum;
});

watch(() => getters.getGoodsNum, (newVal, oldVal) => {
	options[1].info = newVal;
});

const popup = ref(null);
const num = ref(1);
const nodes = ref([]);
const imgList = ref([]);
const detailsId = ref("");
const detailsData = ref([]);
const shufflingData = ref([]);
const options = reactive([
	{
		icon: 'heart',
		text: '收藏',
		infoBackgroundColor: '#ff0000',
		infoColor: "#ff0000"
	},
	{
		icon: 'cart',
		text: '购物车',
		info: 2
	}
]);

const buttonGroup = reactive([
	{
		text: '加入购物车',
		backgroundColor: '#ff0000',
		color: '#fff'
	},
	{
		text: '立即购买',
		backgroundColor: '#ffa200',
		color: '#fff',
	}
])

const onClick = (e) => {
	if (e.content.text === "购物车") {
		uni.switchTab({
			url: "../shoppingCart/shoppingCart"
		});
		return;
	}
	uni.showToast({
		title: `点击${e.content.text}`,
		icon: 'none'
	})
}

const handleChange = (e) => {
	num.value = e;
};

const handleClone = () => {
	popup.value.close();
};

const handleDetermine = () => { // 确定 ==> add购物车
	const { stock } = detailsData.value;
	if (num.value > stock) {
		uni.toast("数量不能超过库存总量");
		return;
	}
	const params = {
		productId: detailsId.value,
		productName: detailsData.value.productName,
		productImg: detailsData.value.headImg,
		num: num.value,
		price: detailsData.value.salePrice
	};
	cartAddCart(params).then(res => {
		if (res.code === 200) {
			uni.toast("添加购物车成功")
			// store.dispatch("handleGetCartData");
			num.value = 1;
			popup.value.close();
			console.log('添加购物车成功');
		}
	})
};

const buttonClick = (e) => {
	console.log(e)
	const typeText = e.content.text;
	if (typeText === "加入购物车") {
		popup.value.open("bottom");
	}
	const type = e.content.text;
	// options[1].info++
};

const handleGetDetails = (id) => { // 获取商品详情
	detailsData.value = [];
	shufflingData.value = [];
	classificationQueryAll({productId: id}).then(res => {
		const { code, data } = res;
		if (code === 200) {
			const imgArr = data.carouselImg && data.carouselImg.split(',');
			imgArr.length && imgArr.forEach(item => {
				shufflingData.value.push({
					imgUrl: item
				})
			});
			nodes.value = formatRichText(data.detail);
			imgList.value = handleGetImgSrc(data.detail);
			detailsData.value = data;
		}
	})
}

const richTextClick = (e) => {
	const item = e.detail.node;
	const src = item && item.attrs.src;
	if (item.name === "img") {
		uni.previewImage({
			current: imgList.value.findIndex(item => item === src),
			urls: imgList.value,
		})
	}
};

const handleGetImgSrc = (richtext) => {
	const imgList = []
	richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		imgList.push(capture)
	})
	return imgList
};

const formatRichText = (html) => {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
	return newContent;
}
</script>

<style lang="scss" scoped>
@import '../../static/css/public.scss';

.goods-nav {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100%;
}

.rich-text {
	padding: 30rpx 0 10rpx 0;
	word-wrap:break-word;
}

.synopsis {
	background-color: #fff;
	padding: 10rpx 30rpx;
	
	.name {
		@include sc(30rpx, #333);
		@include showEllipsis(2);
		padding-bottom: 20rpx;
		padding-top: 10rpx;
		height: 100rpx;
	}
	
	.price {
		text {
			font-weight: bold;
			@include sc(38rpx, #F7831E);
			
			&:last-child {
				padding-left: 20rpx;
				@include sc(22rpx, #999);
				text-decoration:line-through;
			}
		}
	}
}

.details {
	padding: 10rpx 30rpx;
	background-color: #fff;
	margin-top: 20rpx;
	
	.title {
		@include sc(30rpx, #333);
		padding: 20rpx 0;
	}
}

.buy {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0rpx 0rpx;
	position: relative;
	padding: 100rpx 30rpx 180rpx 30rpx;
	
	.close {
		position: absolute;
		top: 34rpx;
		right: 29rpx;
	}
	
	.order-details {
		display: flex;
		
		.left {
			padding-right: 30rpx;
			
			image {
				@include wh(180rpx, 180rpx);
			}
		}
		
		.right {
			.price {
				padding-top: 21rpx;
				font-weight: 500;
				@include sc(30rpx, #F7831E);
			}
			
			.inventory {
				padding-top: 18rpx;
				@include sc(24rpx, #999999);
			}
		}
	}
	
	.quantity {
		padding-top: 100rpx;
		@include fja();
		
		.num {
			@include sc(26rpx, #333);
		}
	}
	
	.button {
		width: 100%;
		position: absolute;
		left: 0;
		bottom: 50rpx;
		padding: 0 30rpx;
		
		view {
			@include lineH(88rpx);
			@include sc(28rpx, #fff);
			text-align: center;
			border-radius: 44rpx;
			background: linear-gradient(90deg, #FC4353, #FF5E41);
		}
	}
}
</style>
